package com.woniu.humanresource.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.woniu.humanresource.dao.ActivityDao;
import com.woniu.humanresource.dao.InterviewerDao;
import com.woniu.humanresource.entity.*;
import com.woniu.humanresource.listener.EmpListener;
import com.woniu.humanresource.listener.InterviewerListener;
import com.woniu.humanresource.service.InterviewerService;
import com.woniu.humanresource.utils.Base64Util;
import com.woniu.humanresource.utils.RealNameAuthentication;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class InterviewerServiceImpl implements InterviewerService {
    @Resource
    InterviewerDao interviewerDao;
    @Resource
    ActivityDao activityDao;
    @Value("${upload.addResourceLocation}")
    private String addResourceLocation;
    @Value("${download.url1}")
    private String downloadUrl;
    @Override
    public void insertInterviewer(Interviewer interviewer) {
//        添加应聘者
        interviewerDao.insertInterviewer(interviewer);
//        添加时间线信息
        Activity activity = new Activity();
        activity.setTimestamp(new Date());
        activity.setContent(interviewer.getContent());
        activity.setIid(interviewer.getId());
        activityDao.insertActivity(activity);
    }

    @Override
    public PageBean<Interviewer> selectCondition(Interviewer interviewer, int pageIndex, int pageSize) {
        List<Interviewer> Interviewer1 = interviewerDao.selectCondition(interviewer, pageIndex, pageSize);
        //        封装为PageBean对象，并设置属性
        PageBean<Interviewer> pageBean=new PageBean<>();
        pageBean.setBeanList(Interviewer1);
        pageBean.setPageSize(pageSize);
        pageBean.setPageIndex(pageIndex);
        pageBean.setBeginEnd();
        pageBean.setTotalRecord(selectConditionCount(interviewer));
        return pageBean;
    }

    @Override
    public int selectConditionCount(Interviewer interviewer) {
        int count = interviewerDao.selectConditionCount(interviewer);
        return count;
    }

    @Override
    public void deleteInterviewer(int id) {
        interviewerDao.deleteInterviewer(id);
    }

    @Override
    public void updateInterviewer(Interviewer interviewer) {
        Activity activity = new Activity();
        if(interviewer.getState()!=null){
            if(interviewer.getState()==1){
                activity.setContent("重新推荐入库");
                activity.setTimestamp(new Date());
                activity.setIid(interviewer.getId());
                activity.setName(interviewer.getAname());
                activityDao.insertActivity(activity);
            }
            if(interviewer.getState()==2){
                activity.setContent("面试通过，进入审核流程");
                activity.setTimestamp(new Date());
                activity.setIid(interviewer.getId());
                activity.setName(interviewer.getAname());
                activityDao.insertActivity(activity);
            }
            if(interviewer.getState()==3){
                activity.setContent("进入人才库");
                activity.setTimestamp(new Date());
                activity.setIid(interviewer.getId());
                activity.setName(interviewer.getAname());
                activityDao.insertActivity(activity);
            }
            if(interviewer.getState()==4){
                activity.setContent("成功入职");
                activity.setTimestamp(new Date());
                activity.setIid(interviewer.getId());
                activity.setName(interviewer.getAname());
                activityDao.insertActivity(activity);
            }
            if(interviewer.getState()==5){
                activity.setContent("离职");
                activity.setTimestamp(new Date());
                activity.setIid(interviewer.getId());
                activity.setName(interviewer.getAname());
                activityDao.insertActivity(activity);
            }
            if(interviewer.getState()==6){
                activity.setContent("进入黑名单");
                activity.setTimestamp(new Date());
                activity.setIid(interviewer.getId());
                activity.setName(interviewer.getAname());
                activityDao.insertActivity(activity);
            }
        }
        interviewerDao.updateInterviewer(interviewer);
    }

    @Override
    public ValidateMsg validateInterviewer(MultipartFile face, String name, String idCard) throws Exception{
//        上传图片
        ValidateMsg validateMsg=new ValidateMsg();
        DateFormat dateFormat=new SimpleDateFormat("yyyy.MM.dd");
        String dateStr = dateFormat.format(new Date());
        File file1 = new File(addResourceLocation+"face."+dateStr);
        if(!file1.exists()){
            file1.mkdirs();
        }
        String path=addResourceLocation+"face."+dateStr;
        String fileName= UUID.randomUUID()+face.getOriginalFilename();
        File file = new File(path,fileName);
        face.transferTo(file);

        //获取人脸路径并转换为base64格式
        String base64 = Base64Util.getBase64(new File(file.getPath()));
        //身份验证
        String result1 = RealNameAuthentication.faceAuthentication(name, idCard, base64);
        //将结果转换为外层结果转换为json
        JSONObject jsonResult = JSON.parseObject(result1);
        Object data = jsonResult.get("data");
        //将内层结果json再转换为String
        String dataStr = JSON.toJSONString(data);
        //获取目标参数
        JSONObject dataJson = JSON.parseObject(dataStr);
        Object messageJson = dataJson.get("message");
        Object resultJson = dataJson.get("result");
        //转换为String
        String message = JSON.toJSONString(messageJson);
        String result = JSON.toJSONString(resultJson);
//        封装为信息类
        validateMsg.setMessage(message);
        validateMsg.setResult(result);
        validateMsg.setIdCard(idCard);
        validateMsg.setName(name);
        return validateMsg;
    }

    @Override
    public void importInterviewer(MultipartFile interviewerExcel) {
        //        上传文件创建文件路径
        DateFormat dateFormat=new SimpleDateFormat("yyyy.MM.dd");
        String dateStr = dateFormat.format(new Date());
        File file1 = new File(addResourceLocation+"interviewerExcel."+dateStr);
        if(!file1.exists()){
            file1.mkdirs();
        }
        String path=addResourceLocation+"interviewerExcel."+dateStr;
        File file = new File(path, UUID.randomUUID()+interviewerExcel.getOriginalFilename());
        try {
            interviewerExcel.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
//            读取文件数据
            ExcelReaderBuilder workBook = EasyExcel.read(file.getPath(), Interviewer.class, new InterviewerListener());
            ExcelReaderSheetBuilder sheet = workBook.sheet();
            sheet.doRead();
//            获得解析的应聘者集合并添加进数据库
        List<Interviewer> interviewerList = InterviewerListener.getInterviewerList();
        for(Interviewer interviewer:interviewerList){
            interviewerDao.insertInterviewer(interviewer);
        }
    }

    @Override
    public void exportInterviewer(HttpServletResponse response) {
        List<Interviewer> interviewers = interviewerDao.selectInterviewerByState(3);
        try {
            ExcelWriterBuilder workBook = EasyExcel.write(downloadUrl, Interviewer.class);
            workBook.sheet().doWrite(interviewers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
